package com.czm.art_light.context;

import com.czm.art_light.param.request.UserActionReqDto;
import com.czm.art_light.patterns.chainOfResponsibility.UserActionHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户行为责任链设计模式管理类
 */
@Component
public class UserActionHandlerChainContext implements ApplicationContextAware {
    private List<UserActionHandler> handlerList = new ArrayList<>();


    //责任链入口方法
    public void execute(UserActionReqDto userActionReqDto) {
        for (UserActionHandler userActionHandler : handlerList) {
            userActionHandler.handle(userActionReqDto);
        }
    }

    //重写ApplicationContextAware方法，从spring容器中获取任务对象，封装到list集合中
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Collection<UserActionHandler> userActionHandlerCollection = applicationContext.getBeansOfType(UserActionHandler.class).values();
        //从spring容器中获取任务对象，封装到handlerList集合中
        handlerList = userActionHandlerCollection.stream()
                .sorted((Comparator.comparingInt(UserActionHandler::sort))).collect(Collectors.toList());
    }
}